package com.daxt.controller.admin;

import java.awt.Color;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.io.FileUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.daxt.base.common.util.RedisUtil;
import com.daxt.base.common.util.UserInfoUtil;
import com.daxt.common.annotations.LoginAuth;
import com.daxt.common.annotations.LoginUser;
import com.daxt.common.exception.BaseException;
import com.daxt.mapper.archives.ArchivesDocFileMapper;
import com.daxt.mapper.sys.WaterMarkMapper;
import com.daxt.model.constant.BaseConstants;
import com.daxt.model.constant.FileExt;
import com.daxt.model.dic.*;
import com.daxt.model.service.archives.vo.ArchivesBehaveLog;
import com.daxt.model.service.archives.vo.ArchivesDocFile;
import com.daxt.model.service.base.result.UserInfo;
import com.daxt.model.service.watermark.WaterMarkConfig;
import com.daxt.service.ArchivesBehaveLogService;
import com.daxt.service.ArchivesService;
import com.daxt.service.UploadService;
import com.daxt.utils.BaseUtil;
import com.daxt.utils.FileValidate;
import com.daxt.utils.file.FileBaseUtil;
import com.itextpdf.text.BaseColor;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.daxt.common.result.Result;
import com.daxt.common.result.ResultCode;
import com.daxt.common.result.ResultUtil;
import com.daxt.utils.FileCopyUtil;
import com.daxt.utils.WaterMarkUtil;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import springfox.documentation.annotations.ApiIgnore;

@Api(tags = "文件上传")
@RestController
public class UploadController {

//    @Value(value = "${systemConfig.tempPath}")
//    private String basePath;
    @Autowired
    private UploadService uploadService;
    @Autowired
    private ArchivesDocFileMapper archivesDocFileMapper;
    @Autowired
    private ArchivesService archivesService;
    @Autowired
    private WaterMarkMapper waterMarkMapper;
    @Autowired
    private UserInfoUtil userInfoUtil;
    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private ArchivesBehaveLogService archivesBehaveLogService;

    ////========================本地上传，公告上传等功能暂时在用
    /**
     * 实现文件上传
     */
    @ApiOperation(value = "公共文件上传", notes = "")
    @PostMapping(value = "/upload")
    public Result<String> upload(@RequestParam("type") String type, @RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "上传文件不能为空", null);
        } else if (!FileType.hasKey(type)) {
            return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "文件类型不存在", null);
        }

        String sysHome = RedisUtil.getSysConfig(SystemConfigType.SYS_HOME);
        String showOssFile = sysHome + "file/";

        try {
            boolean validate = FileValidate.validate(file.getInputStream());
            if (!validate) {
                return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "文件已损坏", null);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }


        Result<String> upload = uploadService.localUpload(BaseConstants.BUCKET_NAME, type,file);
        upload.setData(showOssFile + upload.getData());

        return upload;
    }
//
//    @ApiOperation(value = "私有文件上传", notes = "")
//    @PostMapping(value = "/pupload/{fondsNum}")
//    public Result<String> upload(@PathVariable("fondsNum") String fondsNum, @RequestParam("type") String type,
//                                 @RequestParam(value = "typeNum", required = false) String typeNum,
//                                 @RequestParam("file") MultipartFile file) {
//        if (StringUtils.isEmpty(fondsNum)) {
//            return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "全宗不能为空", null);
//        } else if (file.isEmpty()) {
//            return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "上传文件不能为空", null);
//        } else if (!FileType.hasKey(type)) {
//            return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "文件类型不存在", null);
//        }
//        /*
//         * try { boolean validate = FileValidate.validate(file.getInputStream());
//         * if(!validate) { return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(),
//         * "文件已损坏", null); } } catch (IOException e) { //
//         * block e.printStackTrace(); }
//         */
//        String objName = type;
//        if (!StringUtils.isEmpty(typeNum)) {
//            objName = typeNum + "/" + objName;
//        }
//        // Result<String> upload =
//        // ossService.uploadSaveName("fonds"+fondsNum.toLowerCase(),objName , file);
//
////        Result<String> upload = ossService.uploadSaveName("templet".equals(type) ? "templet" : "temp",
////                "templet".equals(type) ? "templet" : objName, file);
//        Result<String> upload = ossService.upload("templet".equals(type) ? "templet" : "temp", "templet".equals(type) ? "templet" : objName,file);
//        return upload;
//    }



    ////========================存储上传 end
//    /**
//     * 实现文件上传
//     */
//    @ApiOperation(value = "公共文件上传", notes = "")
//    @PostMapping(value = "/upload")
//    public Result<String> upload(@RequestParam("type") String type, @RequestParam("file") MultipartFile file) {
//        if (file.isEmpty()) {
//            return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "上传文件不能为空", null);
//        } else if (!FileType.hasKey(type)) {
//            return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "文件类型不存在", null);
//        }
//        try {
//            boolean validate = FileValidate.validate(file.getInputStream());
//            if (!validate) {
//                return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "文件已损坏", null);
//            }
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        Result<String> upload = ossService.upload(type.toLowerCase(), type, file);
//
//        return upload;
//    }
//
    @ApiOperation(value = "私有文件上传", notes = "")
    @PostMapping(value = "/pupload/{fondsId}")
    public Result<String> upload(@PathVariable("fondsId") String fondsId, @RequestParam("type") String type,
                                 @RequestParam(value = "typeId", required = false) String typeId,
                                 @RequestParam("file") MultipartFile file) {
        if (StringUtils.isEmpty(fondsId)) {
            return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "全宗不能为空", null);
        } else if (file.isEmpty()) {
            return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "上传文件不能为空", null);
        } else if (!FileType.hasKey(type)) {
            return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "文件类型不存在", null);
        }

        String objName = type;
        if (!StringUtils.isEmpty(typeId)) {
            objName = typeId + "/" + objName;
        }

        Result<String> upload = uploadService.localUpload("templet".equals(type) ? "templet" : "temp",
                "templet".equals(type) ? "templet" : objName, file);

        return upload;
    }




//    @ApiOperation(value = "标准文件上传(临时目录)", notes = "")
//    @PostMapping(value = "/upload")
//    public Result<String> upload(@RequestParam("type") String type, @RequestParam("file") MultipartFile file) {
//        if (file.isEmpty()) {
//            return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "上传文件不能为空", null);
//        } else if (!FileType.hasKey(type)) {
//            return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "文件类型不存在", null);
//        }
//
//        Result<String> upload = ossService.upload(type, type,file);
//        return upload;
//    }




//    @ApiOperation(value = "私有文件上传", notes = "")
//    @PostMapping(value = "/pupload/{fondsNum}")
//    public Result<String> upload(@PathVariable("fondsNum") String fondsNum, @RequestParam("type") String type,
//                                 @RequestParam(value = "typeNum", required = false) String typeNum,
//                                 @RequestParam("file") MultipartFile file) {
//        if (StringUtils.isEmpty(fondsNum)) {
//            return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "全宗不能为空", null);
//        } else if (file.isEmpty()) {
//            return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "上传文件不能为空", null);
//        } else if (!FileType.hasKey(type)) {
//            return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "文件类型不存在", null);
//        }
//        /*
//         * try { boolean validate = FileValidate.validate(file.getInputStream());
//         * if(!validate) { return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(),
//         * "文件已损坏", null); } } catch (IOException e) { //
//         * block e.printStackTrace(); }
//         */
//        String objName = type;
//        if (!StringUtils.isEmpty(typeNum)) {
//            objName = typeNum + "/" + objName;
//        }
//        // Result<String> upload =
//        // ossService.uploadSaveName("fonds"+fondsNum.toLowerCase(),objName , file);
//
//        Result<String> upload = ossService.uploadSaveName("templet".equals(type) ? "templet" : "temp",
//                "templet".equals(type) ? "templet" : objName, file);
//        return upload;
//    }

    @ApiOperation(value = "文件上删除", notes = "")
    @DeleteMapping("/upload/{url}")
    public Result<String> removeFile(@PathVariable("url") String url) {
        return uploadService.removeFile(url);
    }


    @ApiOperation(value = "文件上删除通过ID", notes = "")
    @DeleteMapping("/delete/{id}")
    @LoginAuth()
    public Result<String> removeFileById(@ApiIgnore @LoginUser UserInfo loginUser, @PathVariable("id") String id,HttpServletRequest request) {
        List<ArchivesDocFile> list = new ArrayList();
        ArchivesDocFile adf = archivesDocFileMapper.selectById(id);
        if(null != adf){
            list.add(adf);

            Result<String> result=archivesService.deleteFile(list);

            archivesBehaveLogService.saveArchivesBehaveLog(new ArchivesBehaveLog(id, BehaveLogType.DELETE_FILE.getKey(),BehaveLogType.DELETE_FILE.getValue(),"删除了附件"),loginUser ,request);
            return result;
        }
//        if(null != adf){
//            int i = archivesDocFileMapper.deleteById(id);
//            if(i > 0){
//                String ext = FileBaseUtil.getFileNameExt(adf.getFileUrl());
//
//                if(FileBaseUtil.isWord(ext)
//                || FileBaseUtil.isExcel(ext)){
//                    String pdfFile = FileBaseUtil.builFileAllName(FileBaseUtil.getFileNameFront(adf.getFileUrl()),FileExt.pdf.getDesc());
//                    FileUtil.del(new File(SystemConfig.ossDir + pdfFile));
//                }
//                FileUtil.del(new File(SystemConfig.ossDir + adf.getFileUrl()));
//
//                //存储模式
//                String accType = RedisUtil.getSysConfig(SystemConfigType.ACCESSORY_TYPE);
//                if (!StringUtils.isEmpty(accType)) {
//                    if(accType.equals(AccessoryType.TYPE_2.getKey())){
//                        //删除桶里的数据
//                        Result<String> rFile = uploadService.removeFile(adf.getFileUrl());
//                        if(rFile.getCode().equals(ResultCode.RESULT_SUCCESS.getCode())){
//                            System.out.println("删除存储数据（成功）："+rFile.getData());
//                        }else{
//                            System.err.println("删除存储数据（失败）：" + rFile.getData());
//                        }
//
//                    }
//                }
//
//
//                return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), "删除成功！", null);
//            }
//        }
        return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "删除失败！", null);

    }

    // http://127.0.0.1:9000/undefined/file/202012/83ead314-7abe-4f41-a966-4f517cfd3a23.pdf
    @ApiOperation(value = "获取地址", notes = "")
    @GetMapping("/getUrl")
    public Result<String> getCourseUrl(@RequestParam("url") String url) throws IOException {
		/*String newData = url.replace(SystemConfig.ossIp, "");
		String bucketName = newData.substring(0, newData.indexOf("/"));
		String objectName = newData.replace(bucketName, "");
		Result<String> result = ossService.getUrl(bucketName.toLowerCase(), objectName);
		return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), null, result.getData());*/
        return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), "", url);
    }

    @ApiOperation(value = "获取水印地址", notes = "")
    @GetMapping("/getWatermarkUrl/{fileType}")
    public Result<String> getWatermarkUrl(@PathVariable("fileType") String fileType,
                                          @RequestParam("url") String url,
                                          @RequestParam("isWaterMark") boolean isWaterMark,
                                          HttpServletResponse response, HttpServletRequest request) throws IOException {


        String sysHome = RedisUtil.getSysConfig(SystemConfigType.SYS_HOME);
        String ossDir = RedisUtil.getSysConfig(SystemConfigType.OSS_DIR);
        String tempPath = RedisUtil.getSysConfig(SystemConfigType.TEMP_PATH);

        String showOssFile = sysHome +  BaseConstants.FILE_SHOW + "/";
        String objectName = IdWorker.getIdStr();
        try {
            //获取文件
            File downFile = uploadService.gainFile(url);

            String ext = FileBaseUtil.getFileExtName(downFile);
            String tempFile = ossDir + BaseConstants.BUCKET_TEMP_NAME + "/" + IdWorker.getIdStr();
//            String tempFile = basePath + IdWorker.getIdStr();

            String waterMarkStr =  RedisUtil.getSysConfig(SystemConfigType.WATER_MARK).trim();
            String waterMarkSize =  RedisUtil.getSysConfig(SystemConfigType.WATER_MARK_SIZE).trim();
            if (RedisUtil.isAppoint(VersionsMarkType.VERSIONS_5 )){
                UserInfo loginInfo = userInfoUtil.getLoginInfo(UserInfo.class, redisUtil, request);
                if(loginInfo!=null && !StringUtils.isEmpty(loginInfo.getFondsId())){
                    QueryWrapper<WaterMarkConfig> wrapper=new QueryWrapper<>();
                    wrapper.eq("fondsId",loginInfo.getFondsId());
                    WaterMarkConfig waterMark = waterMarkMapper.selectOne(wrapper);
                    if(waterMark!=null){
                        waterMarkStr=waterMark.getWaterMark();
                        waterMarkSize=waterMark.getWaterMarkSize();
                    }
                }
            }

            String[] waterMarkColor = RedisUtil.getSysConfig(SystemConfigType.WATER_MARK_COLOR).trim().split(",");
            int R = 187;
            int G = 187;
            int B = 187;

            if(null != waterMarkColor && waterMarkColor.length==3){
                R = Integer.parseInt(waterMarkColor[0]);
                G = Integer.parseInt(waterMarkColor[1]);
                B = Integer.parseInt(waterMarkColor[2]);
            }

            if ("1".equals(fileType)) {//pdf
                ext = ".pdf";
                //版本标识 lig  2021-06-10
                if(RedisUtil.isAppoint(VersionsMarkType.VERSIONS_2)){
                    objectName = BaseUtil.getFileName(url);
                }
                tempFile = tempFile + ".pdf";

                //增加水印系统配置 lig 2021-06-21
                if(isWaterMark){
                    WaterMarkUtil.waterMark(downFile.getAbsolutePath(),
                            tempFile, waterMarkStr,new BaseColor(R,G,B),waterMarkSize);
                }else{
                    FileUtils.copyFile(downFile, new File(tempFile));
                }

            } else if ("2".equals(fileType)) {//图片
                ext = ".jpg";
//                tempFile = basePath + IdWorker.getIdStr() + ".jpg";
                tempFile = tempFile + ".jpg";
                if(isWaterMark){
                    WaterMarkUtil.mark(downFile.getAbsolutePath(),
                            tempFile, new Color(R, G, B), waterMarkStr);
                }else {
                    FileUtils.copyFile(downFile, new File(tempFile));
                }

            } else if ("3".equals(fileType)) {//视频
                tempFile = downFile.getAbsolutePath();
            } else if ("5".equals(fileType)){//html
                tempFile=tempFile+".html";

                FileUtils.copyFile(downFile, new File(tempFile));
            } else if ("6".equals(fileType)){//xml
                tempFile=tempFile+".xml";
                FileUtils.copyFile(downFile, new File(tempFile));
            }


            //File tempF=new File(tempFile);
            FileInputStream inputStream = new FileInputStream(new File(tempFile));
//            PutObjectOptions options = new PutObjectOptions(inputStream.available(), -1);
//            if (tempFile.toLowerCase().endsWith("pdf".toLowerCase())) {
//                options.setContentType("application/pdf");
//            } else if (tempFile.toLowerCase().endsWith("jpg".toLowerCase())) {
//                options.setContentType("image/jpeg");
//            } else if (tempFile.toLowerCase().endsWith("jpeg".toLowerCase())) {
//                options.setContentType("image/jpeg");
//            } else if (tempFile.toLowerCase().endsWith("png".toLowerCase())) {
//                options.setContentType("image/png");
//            } else if (tempFile.toLowerCase().endsWith("mp3".toLowerCase())) {
//                options.setContentType("audio/mpeg");
//            } else if (tempFile.toLowerCase().endsWith("ogg".toLowerCase())) {
//                options.setContentType("video/x-theora+ogg");
//            } else if (tempFile.toLowerCase().endsWith("mp4".toLowerCase())) {
//                options.setContentType("video/mp4");
//            }
//            String uploadFile = FileCopyUtil.uploadFile("temp", objectName + ext, inputStream, SystemConfig.ossDir);

//            return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), "", SystemConfig.showOssFile + uploadFile);
            return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), "", showOssFile + tempFile.replace(ossDir, ""));


        } catch (Exception e) {
            e.printStackTrace();
            //return null;
        }
        return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "", "");
    }

/*	private File downFile(String fileUrl, String target) throws Exception {
		String replace = fileUrl.replace(SystemConfig.ossIp, "");
		int indexOf = replace.indexOf("/");
		String bucketName = replace.substring(0, indexOf);
		String objectName = replace.substring(indexOf + 1);
		String extName = replace.substring(replace.lastIndexOf("."));
		InputStream downFile = MinioUtil.downFile(bucketName, objectName);
		File f = new File(target + extName);
		if (!f.exists())
			f.createNewFile();
		FileOutputStream out = new FileOutputStream(target + extName);
		// FileOutputStream out=new FileOutputStream("."+File.separator+taskId+".docx");
		int len = 0;
		byte[] b = new byte[512];
		while ((len = downFile.read(b)) > 0) {
			out.write(b, 0, len);
		}
		out.flush();
		downFile.close();
		out.close();
		File file = new File(target + extName);
		return file;
	}*/

}
